class TreeNode{
    public int val;
    public TreeNode left;
    public TreeNode right;

    public TreeNode() {}

    public TreeNode(int val) {
        this.val = val;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q){
        if(root == null){
            return root;
        }

        if(root == p || root == q){
            return root;
        }

        TreeNode leftT = lowestCommonAncestor(root.left,p,q);
        TreeNode rightT = lowestCommonAncestor(root.right,p,q);

        if(leftT != null && rightT != null){//p、q分别在左右子树上
            return root;
        }else if(leftT != null){
            return leftT;
        } else if (rightT != null) {
            return rightT;
        }
        return null;
    }
}
